package ua.org.nuos.sdms.middle.dao;

import org.apache.commons.lang.Validate;
import ua.org.nuos.sdms.middle.entity.Group;
import ua.org.nuos.sdms.middle.util.EntityValidator;
import ua.org.nuos.sdms.middle.util.validator.GroupValidator;

import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 09.10.11
 * Time: 21:31
 * To change this template use File | Settings | File Templates.
 */
@Local
@Stateless
public class GroupDaoBean {

    private static Logger logger = Logger.getLogger(GroupDaoBean.class.getSimpleName());

    @PersistenceContext(unitName = "persistence")
    protected EntityManager em;

    protected GroupValidator validator;

    @PostConstruct
    protected void init() {
        validator = new GroupValidator(em);
    }

    /**
     * Create new group
     *
     * @param group group
     *              Group.name is required
     *              Group.currentDate is required
     */
    public void create(Group group) {
        validator.validate(group);
        em.persist(group);
    }

    /**
     * Update existing group
     *
     * @param group group entity
     */
    public void update(Group group) {
        validator.validatePersisted(group);
        em.merge(group);
    }

    /**
     * Find existing group by id
     *
     * @param groupId group id
     * @return can be null group
     */
    public Group findById(long groupId) {
        Validate.isTrue(groupId > 0);

        return em.find(Group.class, groupId);
    }

    /**
     * Find existing group by name
     *
     * @param name group name
     * @return not null group list
     */
    public List<Group> findByName(String name) {
        Validate.notEmpty(name);

        try {
            return em.createNamedQuery(Group.QUERY_FIND_BY_NAME, Group.class)
                    .setParameter("groupName", name.toLowerCase()).getResultList();
        } catch (NoResultException e) {
            return new LinkedList<Group>();
        }
    }

    public List<Group> findByOrganisation(String organisation) {
        Validate.notEmpty(organisation);

        try {
            return em.createNamedQuery(Group.QUERY_FIND_BY_ORGANISATION, Group.class)
                    .setParameter("organisation", organisation.toLowerCase()).getResultList();
        } catch (NoResultException e) {
            return new LinkedList<Group>();
        }
    }

    /**
     * Remove existing group
     *
     * @param groupId group id
     */
    public void remove(long groupId) {
        Validate.isTrue(groupId > 0);

        Group group = em.find(Group.class, groupId);
        EntityValidator.checkExisting(group, groupId);

        em.remove(group);
    }


}
